import { Mark, mergeAttributes } from '@tiptap/core'

export default Mark.create({
  name: 'link',

  priority: 1000,

  keepOnSplit: false,

  addOptions() {
    return {
      openOnClick: true,
      linkOnPaste: true,
      autolink: true,
      protocols: [],
      HTMLAttributes: {},
      validate: undefined
    }
  },

  addAttributes() {
    return {
      href: {
        default: null
      },
      target: {
        default: this.options.HTMLAttributes.target
      },
      rel: {
        default: null
      },
      title: {
        default: null
      },
      class: {
        default: null
      }
    }
  },

  parseHTML() {
    return [{ tag: 'a[href]:not([href *= "javascript:" i])' }]
  },

  renderHTML({ HTMLAttributes }) {
    // 确保外部链接有适当的安全属性
    if (HTMLAttributes.href &&
        (HTMLAttributes.href.startsWith('http://') || HTMLAttributes.href.startsWith('https://')) &&
        !HTMLAttributes.href.includes(window.location.hostname)) {
      // 如果没有设置rel，默认为noopener
      if (!HTMLAttributes.rel) {
        HTMLAttributes.rel = 'noopener'
      }
      // 如果设置了target="_blank"但没有rel，添加安全属性
      if (HTMLAttributes.target === '_blank' && !HTMLAttributes.rel.includes('noopener')) {
        HTMLAttributes.rel += ' noopener'
      }
    }

    return [
      'a',
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
      0
    ]
  },

  addCommands() {
    return {
      setLink: attributes => ({ chain }) => {
        return chain()
          .setMark(this.name, attributes)
          .setMeta('preventAutolink', true)
          .run()
      },

      toggleLink: attributes => ({ chain }) => {
        return chain()
          .toggleMark(this.name, attributes, { extendEmptyMarkRange: true })
          .setMeta('preventAutolink', true)
          .run()
      },

      unsetLink: () => ({ chain }) => {
        return chain()
          .unsetMark(this.name, { extendEmptyMarkRange: true })
          .setMeta('preventAutolink', true)
          .run()
      }
    }
  },

  addKeyboardShortcuts() {
    return {
      'Mod-k': () => this.editor.commands.toggleLink()
    }
  }
})
